﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QLNHK.BLL;
using System.Threading;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;

namespace QLNHK
{
    public partial class frmQuanLyHoKhau : frmBase_Rebind
    {
        private DataSet dsData = new DataSet();
        private string whereCondition, orderBy;
        private int tongSoNhanKhau, tongSoHoKhau;
        frmWait frmWaiting;

        #region Set Authentication On Form
        private cls_Role ObjRole = null;
        private Cls_PHANQUYEN_NHOM ObjPhanQuyen = null;
        private Infragistics.Win.DefaultableBoolean GetStatus(bool values)
        {
            if (values)
            {
                return Infragistics.Win.DefaultableBoolean.True;
            }
            else
            {
                return Infragistics.Win.DefaultableBoolean.False;
            }
        }
        private void SetAuthenticationOnForm()
        {
            try
            {
                if (!frmMain.ObjNguoiDung.IsAdministrator)
                {
                    ObjRole = new cls_Role();
                    ObjPhanQuyen = new Cls_PHANQUYEN_NHOM();

                    ObjRole = new cls_Role(Global.GetRole(ObjPhanQuyen.GetRoleByIDChucNang(frmMain.ObjNguoiDung.ID_NguoiDung, this.Tag.ToString())));

                    if (ObjRole != null)
                    {
                        if (ObjRole.HienThi == false)//không hiển thị
                        {
                            foreach (Control ctl in this.Controls)
                            {
                                ctl.Visible = false;
                            }
                        }
                        //chỉ cho phép hiển thị, không cho phép cập nhật, sửa, xóa
                        else if (ObjRole.HienThi == true && ObjRole.Them == false && ObjRole.Sua == false && ObjRole.Xoa == false)
                        {
                            //Grid tom tat ban than
                            gridHoKhau.DisplayLayout.Bands[0].Override.AllowDelete = GetStatus(ObjRole.Xoa);
                            gridHoKhau.DisplayLayout.Bands[0].Override.AllowUpdate = GetStatus(ObjRole.Sua);
                            if (ObjRole.Them)
                                gridHoKhau.DisplayLayout.Bands[0].Override.AllowAddNew = AllowAddNew.TemplateOnTopWithTabRepeat;

                            btnAdd.Enabled = ObjRole.Them;
                            btnEdit.Enabled = ObjRole.Sua;
                            btnDel.Enabled = ObjRole.Xoa;
                        }
                        //cho phép hiển thị, cho phép hoặc cập nhật, hoặc sửa, hoặc xóa
                        else
                        {
                            CheckAuthentication();
                        }
                    }
                }

                btnClose.Enabled = true;
            }

            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
        }
        private void CheckAuthentication()
        {
            try
            {
                if (ObjRole != null)
                {
                    //Grid tom tat ban than
                    gridHoKhau.DisplayLayout.Bands[0].Override.AllowDelete = GetStatus(ObjRole.Xoa);
                    btnDel.Enabled = ObjRole.Xoa;

                    gridHoKhau.DisplayLayout.Bands[0].Override.AllowUpdate = GetStatus(ObjRole.Sua);
                    btnEdit.Enabled = ObjRole.Sua;

                    if (ObjRole.Them)
                        gridHoKhau.DisplayLayout.Bands[0].Override.AllowAddNew = AllowAddNew.TemplateOnTopWithTabRepeat;
                    else
                        gridHoKhau.DisplayLayout.Bands[0].Override.AllowAddNew = AllowAddNew.No;
                    btnAdd.Enabled = ObjRole.Them;
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
        }
        #endregion

        public frmQuanLyHoKhau()
        {
            InitializeComponent();
        }
        private void frmQuanLyHoKhau_Load(object sender, EventArgs e)
        {
            try
            {
                btnClear.PerformClick();

                frmWaiting = new frmWait();
                ThreadPool.QueueUserWorkItem(OnProcess);
                frmWaiting.ShowDialog(this);
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private void OnProcess(object o)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    frmWaiting.SetCaption("Vui lòng chờ giây lát");

                    //Load data tại đây
                    this.LoadData(ref frmWaiting);
                    frmWaiting.DialogResult = DialogResult.OK;
                }));
            }
        }

        private void cboThanhPho_ValueChanged(object sender, EventArgs e)
        {
            if (cboThanhPho.Value != null)
            {
                int cboThanhPhoValue = 0;
                Int32.TryParse(cboThanhPho.Value.ToString(), out cboThanhPhoValue);
                if (cboThanhPhoValue > 0)
                    Global.setDataToComboQuanHuyen(cboQuanHuyen, Convert.ToInt32(cboThanhPho.Value));
            }
        }
        private void cboQuanHuyen_ValueChanged(object sender, EventArgs e)
        {
            if (cboQuanHuyen.Value != null)
            {
                int cboQuanHuyenValue = 0;
                Int32.TryParse(cboQuanHuyen.Value.ToString(), out cboQuanHuyenValue);
                if (cboQuanHuyenValue > 0)
                    Global.setDataToComboXaPhuong(cboXaPhuong, Convert.ToInt32(cboQuanHuyen.Value));
            }
        }
        private void cboXaPhuong_ValueChanged(object sender, EventArgs e)
        {
            if (cboXaPhuong.Value != null)
            {
                int cboXaPhuongValue = 0;
                Int32.TryParse(cboXaPhuong.Value.ToString(), out cboXaPhuongValue);
                if (cboXaPhuongValue > 0)
                    Global.setDataToComboToDanPho(cboToDanPho, Convert.ToInt32(cboXaPhuong.Value));
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                txtSoSoHK.Text = txtSoHSHK.Text = txtHoTen.Text = txtDiaChi.Text = string.Empty;
                //Set dia ban
                Global.setDataToComboDanhMuc(cboLoaiHoKhau, DMCatalogue.DM_LOAIHOKHAU);
                Global.setDataToComboThanhPho(cboThanhPho);
                cboThanhPho.Value = ConfigNHK.Install.ThanhPho; // Global.DIABAN_THANHPHO;
                txtHoTen.Focus();
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            frmWaiting = new frmWait();
            ThreadPool.QueueUserWorkItem(OnProcess);
            frmWaiting.ShowDialog(this);
        }
        private void LoadData(ref frmWait frmW)
        {
            try
            {
                //Load data
                whereCondition = "1=1";
                //So so ho khau
                if (txtSoSoHK.Text.Trim().Length > 0)
                {
                    if (chkTimChinhXac.Checked)
                        whereCondition += " AND SoSoHoKhau = " + txtSoSoHK.Text.Trim();
                    else
                        whereCondition += " AND SoSoHoKhau like '%" + txtSoSoHK.Text.Trim() + "%'";
                }
                //So ho so ho khau
                if (txtSoHSHK.Text.Trim().Length > 0)
                {
                    if (chkTimChinhXac.Checked)
                        whereCondition += " AND HSHKSo = " + txtSoHSHK.Text.Trim();
                    else
                        whereCondition += " AND HSHKSo like '%" + txtSoHSHK.Text.Trim() + "%'";
                }
                //Ho ten
                if (txtHoTen.Text.Trim().Length > 0)
                {
                    if (chkTimChinhXac.Checked)
                        whereCondition += " AND (HoLot = N'" + txtHoTen.Text.Trim() + "' OR Ten = N'" + txtHoTen.Text.Trim() + "')";
                    else
                        whereCondition += " AND (HoLot like N'%" + txtHoTen.Text.Trim() + "%' OR Ten like N'%" + txtHoTen.Text.Trim() + "%')";
                }
                //Dia chi
                if (txtDiaChi.Text.Length > 0)
                {
                    if (chkTimChinhXac.Checked)
                        whereCondition += string.Format(" AND (DiaChi = N'{0}')", txtDiaChi.Text);
                    else
                        whereCondition += string.Format(" AND (DiaChi like N'%{0}%')", txtDiaChi.Text);
                }
                //Tinh trang
                if (System.Convert.ToInt32(cboLoaiHoKhau.Value) > 0)
                    whereCondition += " AND (LoaiHoKhauID = " + System.Convert.ToInt32(cboLoaiHoKhau.Value) + ")";

                if (System.Convert.ToInt32(cboThanhPho.Value) > 0)
                    whereCondition += string.Format(" AND (TinhTPID = {0})", cboThanhPho.Value);
                if (System.Convert.ToInt32(cboQuanHuyen.Value) > 0)
                    whereCondition += string.Format(" AND (QuanHuyenID = {0})", cboQuanHuyen.Value);
                if (System.Convert.ToInt32(cboXaPhuong.Value) > 0)
                    whereCondition += string.Format(" AND (PhuongXaID = {0})", cboXaPhuong.Value);
                if (System.Convert.ToInt32(cboToDanPho.Value) > 0)
                    whereCondition += string.Format(" AND (ToDanPhoID = {0})", cboToDanPho.Value);

                orderBy = "SoSoHoKhau asc";
                dsData = HoKhau.SearchBy(whereCondition, orderBy);
                gridHoKhau.DataSource = dsData.Tables[0];

                tongSoHoKhau = dsData.Tables[0].Rows.Count;
                // Declare an object variable.
                object sumObject;
                sumObject = dsData.Tables[0].Compute("Sum(SoNhanKhau)", "");
                lblTongSo.Text = string.Format("Tổng số hộ khẩu: {0} - nhân khẩu: {1}", tongSoHoKhau, (sumObject == System.DBNull.Value ? "0" : sumObject.ToString()));

                //Kiem tra phan quyen sau khi nap du lieu
                SetAuthenticationOnForm();
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void gridHoKhau_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            try
            {
                e.Layout.Override.CellClickAction = CellClickAction.RowSelect;

                UltraGridBand band = e.Layout.Bands[0];
                band.Columns["ID"].Hidden = true;
                band.Columns["CanBoQuanLyID"].Hidden = true;
                band.Columns["ThuongTru"].Header.Caption = "Thường trú";

                band.Columns["LoaiHoKhauID"].ValueList = Global.getValueListDanhMuc(DMCatalogue.DM_LOAIHOKHAU);
                band.Columns["LoaiHoKhauID"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
                band.Columns["LoaiHoKhauID"].CellActivation = Activation.NoEdit;

                band.Columns["SoSoHoKhau"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
                band.Columns["HSHKSo"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
                band.Columns["SoNhanKhau"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private void gridHoKhau_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            EditHoKhau();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //Open form to edit
            frmThemMoiHoKhau frm = new frmThemMoiHoKhau();
            frm.ShowDialog();

            //Update row add on grid
            frmWaiting = new frmWait();
            ThreadPool.QueueUserWorkItem(OnProcess);
            frmWaiting.ShowDialog(this);
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            EditHoKhau();
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                if (gridHoKhau.ActiveRow != null && gridHoKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    string soSoHK = gridHoKhau.ActiveRow.Cells["SoSoHoKhau"].Value.ToString();
                    //Get ID nhan khau
                    int hkID = System.Convert.ToInt32(gridHoKhau.ActiveRow.Cells["ID"].Value);

                    //Kiem tra ho khau co nhan khau khong?
                    if (NhanKhau.SelectCollectionBy_HoKhauID(hkID).Count > 0)
                    {
                        MessageBox.Show("Hiện có thông tin nhân khẩu trong hộ khẩu '" + soSoHK + "' này, bạn không thể xóa. \r\n\nBạn phải xóa thông tin nhân khẩu trước khi xóa hộ khẩu này.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        HoKhau editNK = HoKhau.Load(hkID);

                        //Open form to edit
                        frmThemMoiHoKhau frm = new frmThemMoiHoKhau();
                        frm.ObjHoKhau = editNK;
                        frm.ShowDialog();

                        btnTimKiem.PerformClick();
                        return;
                    }

                    //Truong hop khong co nha khau nao:
                    if (DialogResult.OK == MessageBox.Show("Bạn có chắc chắn muốn xóa thông tin hộ khẩu '" + soSoHK + "' này không?.", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        HoKhau.DeleteHoKhau(hkID);

                        MessageBox.Show("Đã xóa thành công thông tin hộ khẩu '" + soSoHK + "'.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        btnTimKiem.PerformClick();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show("Lỗi trong quá trình xóa thông tin hộ khẩu: " + ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void EditHoKhau()
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                if (gridHoKhau.ActiveRow != null && gridHoKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    //Get ID nhan khau
                    int nkID = System.Convert.ToInt32(gridHoKhau.ActiveRow.Cells["ID"].Value);
                    HoKhau editNK = HoKhau.Load(nkID);

                    //Open form to edit
                    frmThemMoiHoKhau frm = new frmThemMoiHoKhau();
                    frm.ObjHoKhau = editNK;
                    frm.ShowDialog();

                    //Update row add on grid
                    frmWaiting = new frmWait();
                    ThreadPool.QueueUserWorkItem(OnProcess);
                    frmWaiting.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            XuatExcel("Danh sach ho khau", saveFileDialog1, excelExporter, Infragistics.Excel.WorkbookFormat.Excel97To2003, gridHoKhau);
        }
        private void XuatExcel(
            string fileName,
            SaveFileDialog saveDialog,
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter exporter,
            Infragistics.Excel.WorkbookFormat excelType,
            Infragistics.Win.UltraWinGrid.UltraGrid grid)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                saveDialog.FileName = fileName;
                saveDialog.Filter = "Excel files (*.xls, *.xlxs)|*.xls;*.xlxs";
                if (DialogResult.OK == saveDialog.ShowDialog())
                {
                    if (saveDialog.FileName.Length > 0)
                    {
                        excelExporter.Export(grid, saveDialog.FileName, excelType);

                        if (DialogResult.OK == MessageBox.Show("Bạn có muốn mở tệp tin Excel được xuất ra không?", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                        {
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void frmQuanLyHoKhau_DiaBanChanged()
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                cboThanhPho.Value = Global.CACHE_THANHPHO_ID;
                cboQuanHuyen.Value = Global.CACHE_QUANHUYEN_ID;
                cboXaPhuong.Value = Global.CACHE_XAPHUONG_ID;
                cboToDanPho.Value = Global.CACHE_TODANPHO_ID;

                btnTimKiem.PerformClick();
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
    }
}
